package com.webflux.tm.webflux.module.test.init2;

import com.webflux.tm.webflux.module.test.init.User;
import com.webflux.tm.webflux.module.test.init.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author Surging
 * @version 1.0
 * @ClassName UserHandler
 * @date 2023-05-09 9:53
 * @desc
 */
public class UserHandler {

    @Autowired
    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    public Mono<ServerResponse> getUserById(ServerRequest request) {
        int userId = Integer.parseInt(request.pathVariable("id"));
        //空值处理
        Mono<ServerResponse> notFount = ServerResponse.notFound().build();
        Mono<User> userMono = this.userService.selectById(userId);
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(userMono, User.class)
                .switchIfEmpty(notFount);
    }

    public Mono<ServerResponse> getAllUsers(ServerRequest request) {
        Flux<User> users = this.userService.selectAllUsers();
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(users, User.class);
    }
}
